package com.lsh.airticket.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageInfo;
import com.lsh.airticket.dao.OrderDao;
// import com.lsh.airticket.dao.TicketDao;
// import com.lsh.airticket.dao.UserDao;
import com.lsh.airticket.dto.OrderInfo;
import com.lsh.airticket.entity.Order;
import com.lsh.airticket.exception.UserException;
import com.lsh.airticket.feign.FlightsFeign;
import com.lsh.airticket.feign.UsersFeign;
import com.lsh.airticket.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author lsh
 * @date 2021/2/19
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;

    // @Autowired
    // TicketDao ticketDao;
    @Autowired
    FlightsFeign ticketDao;

    // @Autowired
    // UserDao userDao;
    @Autowired
    UsersFeign userDao;

    @Override
    public int addOrder(Order order) {
        order.setOrderCreatetime(new Date());
        Integer orderPrice = order.getOrderPrice();
        Integer realTicketPrice = ticketDao.findTbTicketById(order.getTicketId()).getTicketPrice();
        System.out.println(realTicketPrice);
        order.setOrderId(RandomUtil.randomNumbers(16));
        order.setOrderPayTime(new Date());
        order.setOrderState("已支付");
        if (!orderPrice.equals(realTicketPrice)) {
            throw new UserException("支付失败, 价格发生变动。");
        }
        int i = orderDao.insertTbOrder(order);
        return i;
    }

    @Override
    public List<Order> findOrderByUserId(Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        return orderDao.findTbOrderByCondition(map);
    }

    @Override
    public PageInfo<OrderInfo> findAll() {
        ArrayList<OrderInfo> orderInfos = new ArrayList<>();
        List<Order> tbOrderAll = orderDao.findTbOrderAll();
        PageInfo<Order> orderPageInfo = new PageInfo<>(tbOrderAll);

        for (Order order : tbOrderAll) {
            String userChname = userDao.findTbUserById((int) (long) order.getUserId()).getUserChname();
            OrderInfo orderInfo = new OrderInfo();
            BeanUtil.copyProperties(order, orderInfo);
            orderInfo.setUserName(userChname);
            orderInfos.add(orderInfo);
        }
        PageInfo<OrderInfo> orderInfoPageInfo = new PageInfo<>();
        BeanUtil.copyProperties(orderPageInfo, orderInfoPageInfo);
        orderInfoPageInfo.setList(orderInfos);
        return orderInfoPageInfo;
    }
}
